import configparser
import json
import os
import sys
sys.path.append(os.path.abspath('.'))
from puzzle import generate_derangement, Puzzle
import random
import argparse

random.seed(202503210932)

def parse_ini_to_json(ini_path):
    config = configparser.ConfigParser()
    config.read(ini_path, encoding="utf-8")

    levels = []
    level_names = [section for section in config.sections() if section != "Metadata"]
    global_source = config["Metadata"]["global_source"]

    for h, level_name in enumerate(level_names):
        i = h + 1
        level_data = config[level_name]

        key = generate_derangement()
        letter_mappings = {}
        for hint in level_data.get("letter_hints", []):
            letter_mappings[key[hint]] = hint
        source = level_data.get("source", global_source)

        if 'quote' in level_data:
            puzzle = Puzzle({"quote": level_data.get("quote"), "source": source}, key, letter_mappings)
        else:
            puzzle = None

        levels.append({
            "id": str(i),
            "index": h + 10,
            "name": level_name,
            "pre_narrative": level_data.get("pre_narrative").split('\\n') if "pre_narrative" in level_data else None,
            "post_narrative": level_data.get("post_narrative").split('\\n') if "post_narrative" in level_data else None,
            "next_level": str(i + 1) if (h + 1) < len(level_names) else None,
            "ending": "win" if h == len(level_names) - 1 else None,
            "choices": None,
            "puzzle": None if puzzle is None else {
                "encrypted_text": puzzle.encrypted_text,
                "decrypted_text": puzzle.decrypted_text,
                "quote": puzzle.quote,
                "key": puzzle.key,
                "letter_mappings": puzzle.letter_mappings
             }
        })

    return {
        "name": config["Metadata"]["name"],
        "id": config["Metadata"]["id"],
        "init_level": "1",
        "levels": levels
    }


def read_and_combine_files(directory):
    combined_data = []

    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)

        if os.path.isfile(filepath):
            result = parse_ini_to_json(filepath)
            combined_data.append(result)

    return combined_data

def main():
    parser = argparse.ArgumentParser(description="Combine story.ini files from a directory into a combined stories.json file.")
    parser.add_argument("input_dir", help="Directory containing the story.ini files to combine")
    parser.add_argument("output_file", help="Output stories.json file name")

    args = parser.parse_args()

    if not os.path.isdir(args.input_dir):
        print("Error: Provided directory does not exist.")
        return

    combined_data = read_and_combine_files(args.input_dir)

    with open(args.output_file, "w", encoding="utf-8") as json_file:
        json.dump(combined_data, json_file, indent=4)

    print(f"Combined data written to {args.output_file}")

if __name__ == "__main__":
    main()
